const { Controller } = require("egg");
const checkUserAgent = require("../util/checkUserAgent");

class BookController extends Controller {
    //添加书籍
    async create() {
            try {
                const body = this.ctx.request.body
                body.orderby = Number(body.orderby)
                await this.ctx.service.book.addBook(body)
                this.ctx.body = {
                    code: 20000,
                    message: true,
                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false
                }
            }
        }
        //查看所有书籍
    async index() {
        try {
            const query = this.ctx.request.query
            const data = await this.ctx.service.book.getBook(query)
            this.ctx.body = {
                code: 20000,
                message: true,
                data: data
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }


    //删除书籍
    async destroy() {
        try {
            const id = this.ctx.params.id
            await this.ctx.service.book.deleteBook(id)
            this.ctx.body = {
                code: 20000,
                message: true,
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }

    //更新书籍
    async update() {
        try {
            const body = this.ctx.request.body
            const id = this.ctx.params.id
            await this.ctx.service.book.updateBook(id, body)
            this.ctx.body = {
                code: 20000,
                message: true,
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }

    async getBookList() {
        const { ctx } = this;
        const ua = checkUserAgent(this.ctx.header['user-agent'])
        let data = await this.ctx.service.website.getBookList()
        if (ua) {
            await this.ctx.render("pc/book.html", data)
        } else {
            await ctx.render("mobile/book.html",data)
        }

    }
}

module.exports = BookController